package com.cn.qgx428.orderingmeal.fragment;


import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.ImageView;
import android.widget.Toast;

import com.cn.qgx428.orderingmeal.R;
import com.cn.qgx428.orderingmeal.adapter.SearchFoodAdatper;
import com.cn.qgx428.orderingmeal.db.LocalFood;
import com.cn.qgx428.orderingmeal.myClass.Food;
import com.cn.qgx428.orderingmeal.myClass.MyKeyInfo;

import org.litepal.crud.DataSupport;

import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;

/**
 * A simple {@link Fragment} subclass.
 */
public class SearchFragment extends Fragment implements View.OnClickListener {
    private static final String TAG="SearchFragment";

    private MyKeyInfo keyInfo;

    private View view = null;

    private List<Food> foodList;
    private List<LocalFood> locaoFoodList;

    private AutoCompleteTextView autoSearch;
    private ArrayAdapter<String> arrayAdatpter;
    private List<String> prompt;
    private ImageView searchBtn;

    private RecyclerView recyler;
    private SearchFoodAdatper foodAdapter;
    private LinearLayoutManager layoutManager;

    private static final int IS_FIRST_SEARCH = 1;
    private static final int NOT_FIRST_SEARCH = 0;
    private int SEARCH_FOOD = IS_FIRST_SEARCH; //首次搜索和其他次搜索分开处理
    public SearchFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.fragment_search, container, false);
        Bmob.initialize(getActivity(),"1b925fe2ccbb402f4034a3e28c31ad93");
        init();
        return view;
    }

    private void init() {
        DataSupport.deleteAll(LocalFood.class);

        keyInfo = (MyKeyInfo)getActivity().getIntent().getSerializableExtra("keyInfo");

        recyler = (RecyclerView) view.findViewById(R.id.search_recycler);
        layoutManager = new LinearLayoutManager(getActivity());
        recyler.setLayoutManager(layoutManager);

        autoSearch = (AutoCompleteTextView) view.findViewById(R.id.search_searchText);
        autoSearch.setThreshold(1);
        searchBtn = (ImageView) view.findViewById(R.id.search_searchBtnImg);
        searchBtn.setOnClickListener(this);
        prompt = new ArrayList<String>();

        //获取食物数据
        BmobQuery<Food> query = new BmobQuery<Food>();
        query.include("shop");
        query.setLimit(100);
        query.findObjects(new FindListener<Food>() {
            @Override
            public void done(List<Food> list, BmobException e) {
                if (e == null){
                    foodList = list;
                    locaoFoodList = new ArrayList<LocalFood>();
                    int position = 0;
                    for(Food food : list){
                        LocalFood localFood = new LocalFood();
                        localFood.setShopName(food.getName());
                        localFood.setShopID(food.getObjectId());
                        localFood.setPosition(position);
                        position++;
                        locaoFoodList.add(localFood);
                        prompt.add(food.getName());

                    }
                    arrayAdatpter = new ArrayAdapter<String>(getActivity(),R.layout.support_simple_spinner_dropdown_item,prompt);
                    autoSearch.setAdapter(arrayAdatpter);
                    DataSupport.saveAll(locaoFoodList);


                } else {
                    Toast.makeText(getActivity(), "服务器出错", Toast.LENGTH_SHORT).show();
                    Log.d(TAG, "获取食物数据失败: "+e.getErrorCode()+e.getMessage());
                }
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.search_searchBtnImg:
                changeRecycler();
                break;
        }
    }

    private void changeRecycler() {
        /**
         * 服务器不提供模糊搜索，故处理方式为，从服务器获取所有数据，添加至本地数据库
         * 使用本地数据库进行模糊搜索，本地数据库记住数据ID,名字，所在返回数据容器的位置
         * 在每次启动前将数据库进行删除，进行“伪更新”
         *
         * 获取符合模糊搜索食物名在foodlist表的位置，取出添加至适配器
         */
        String searchString = autoSearch.getText().toString();
        List<LocalFood> ls = DataSupport.where("shopName like ?","%"+searchString+"%").find(LocalFood.class);
        List<Food> searchFoods = new ArrayList<Food>();
        for(LocalFood food : ls){
            searchFoods.add(foodList.get(food.getPosition()));
        }
        if (SEARCH_FOOD == IS_FIRST_SEARCH){
            foodAdapter = new SearchFoodAdatper(getActivity(),getActivity(),searchFoods,keyInfo);
            recyler.setAdapter(foodAdapter);
            SEARCH_FOOD = NOT_FIRST_SEARCH;
        } else if(SEARCH_FOOD == NOT_FIRST_SEARCH){
            foodAdapter.changeAdapter(searchFoods);
        }
    }
}
